﻿using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Collections;

namespace Elvex
{
    [RequireComponent(typeof(AssetsPool))]
    public class AssetManager : MonoSingleton<AssetManager>
    {
        public AssetsConfiguration Configuration { get; } = new AssetsConfiguration();

        public AssetsPool m_assetsPool;

        private void Awake()
        {
            DontDestroyOnLoad(gameObject);
        }

#if UNITY_EDITOR
        public AssetRequest LoadAssetAsync(string path)
        {
            AssetRequest req = new AssetRequest();
            StartCoroutine(LoadAssetAsync(path, req));
            return req;
        }

        private IEnumerator LoadAssetAsync(string path, AssetRequest req)
        {
            yield return null;
            req.Asset = AssetDatabase.LoadMainAssetAtPath(path);
            req.OnCompleted();
        }

        public AssetRequest<T> LoadAssetAsync<T>(string path) where T : UnityEngine.Object
        {
            AssetRequest<T> req = new AssetRequest<T>();
            StartCoroutine(LoadAsync<T>(path, req));
            return req;
        }

        private IEnumerator LoadAsync<T>(string path, AssetRequest<T> req) where T : UnityEngine.Object
        {
            yield return null;
            req.Asset = AssetDatabase.LoadAssetAtPath<T>(path);
            req.OnCompleted();
        }

        public AssetsRequest LoadAssetsAsync(List<string> paths)
        {
            var req = new AssetsRequest
            {
                AssetsCount = paths.Count
            };
            StartCoroutine(LoadAssetsAsync(paths, req));
            return req;
        }

        private IEnumerator LoadAssetsAsync(List<string> paths, AssetsRequest req)
        {
            yield return null;
            foreach (var path in paths)
            {
                req.OnAssetCompleted(AssetDatabase.LoadMainAssetAtPath(path));
            }
            req.OnCompleted();
        }

        public AssetsRequest<T> LoadAssetsAsync<T>(List<string> paths) where T : UnityEngine.Object
        {
            var req = new AssetsRequest<T>
            {
                AssetsCount = paths.Count
            };
            StartCoroutine(LoadAssetsAsync(paths, req));
            return req;
        }

        private IEnumerator LoadAssetsAsync<T>(List<string> paths, AssetsRequest<T> req) where T : Object
        {
            yield return null;
            foreach(var path in paths)
            {
                req.OnAssetCompleted(AssetDatabase.LoadAssetAtPath<T>(path));
            }
            req.OnCompleted();
        }
#endif

        private void Start()
        {
            //Debug.Log("Addressables Init");
            //UnityEngine.AddressableAssets.Addressables.InitializeAsync();
        }

        private void Update()
        {
            
        }
    }
}
